<template>
	<div style="display: flex;">
		<el-container style="height: 100vh">
			<el-menu default-active="1" @select='selectINdex' active-text-color='#ffffff' class="el-menu-vertical-demo"
				style="background-color: rgb(138,156,232); height: 90%;overflow-x: hidden">
				<div style="height: 60px;line-height: 60px;text-align: center">
					<b style="color:black" v-show="logoTextShow">图书馆管理</b>
				</div>
				<el-menu-item index="1">
					<el-icon>
						<Reading />
					</el-icon>
					<span>书籍列表</span>
				</el-menu-item>
				<el-menu-item index="3">
					<el-icon>
						<document />
					</el-icon>
					<span>借阅记录</span>
				</el-menu-item>
				<el-menu-item index="2">
					<el-icon>
						<location />
					</el-icon>
					<span>座位列表</span>
				</el-menu-item>
				<el-menu-item index="4">
					<el-icon>
						<setting />
					</el-icon>
					<span>座位预定记录</span>
				</el-menu-item>
			</el-menu>
		</el-container>
		<el-main>
			<el-dialog title="选择时间" v-model="timePick" width="50%">
				<el-date-picker v-model="timeData" type="daterange" range-separator="至" start-placeholder="开始日期"
					end-placeholder="结束日期">
				</el-date-picker>
				<div slot="footer" class="dialog-footer"
					style="margin-top: 20px;display: flex;align-items: center;justify-content: center;">
					<el-button @click="timePick = false">取 消</el-button>
					<el-button type="primary" @click="confirmJyTime">确 定</el-button>
				</div>
			</el-dialog>
			<el-dialog title="选择座位预定时间" v-model="seatPick" width="50%">
				<div style="display: flex;flex-direction: column;;justify-content: center;width: 100%;">
					<div style="color: #ff0000;margin-bottom: 10px;font-size: 12px;">*只显示可预约时间</div>
					<el-select v-model="seatData" @change='changeSeatTime' multiple placeholder="请选择" style="width: 100%;">
						<el-option v-for="item in seatTimeList" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</div>
				<div slot="footer" class="dialog-footer"
					style="margin-top: 20px;display: flex;align-items: center;justify-content: center;">
					<el-button @click="seatPick = false">取 消</el-button>
					<el-button type="primary" @click="confirmSeatTime">确 定</el-button>
				</div>
			</el-dialog>
			<el-card class="box-card" v-if="indexSel==1">
				<template #header>
					<div class="card-header">
						<el-input v-model="keyWord" placeholder="请输入书籍名称" style="width: 200px;margin-right: 20px;" />
						<el-button type="primary" @click="currentPage=1,tableData.length=0,getBooks()">搜索</el-button>
            <el-button type="primary" @click="translationStart" >开始录音
              <el-icon><Microphone /></el-icon>
            </el-button>
            <el-button type="primary" @click="translationStop" >结束录音
              <el-icon><Mute /></el-icon>
            </el-button>
            <span style="font-size: 16px; color: #336699;margin-left: 20px;margin-top: 5px">归还提醒：请注意借阅时长，在规定时间内归还</span>

          </div>
				</template>
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="bookNo" label="编号" align="center" />
					<el-table-column prop="bookName" label="名称" align="center" />
					<el-table-column prop="bookAuthor" label="作者" align="center" />
					<el-table-column prop="bookPubHouse" label="出版社" align="center" />
					<el-table-column label="操作" align="center">
						<template v-slot="scope">
							<el-button type="primary" @click="showJyPick(scope.row)">借阅</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination style="margin-top: 20px;" background layout="prev, pager, next" :total="total"
					@current-change='currentChange' :page-size="5">
				</el-pagination>
			</el-card>
			<el-card class="box-card" v-if="indexSel==2">
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="seatNo" label="座位编号" align="center" />
					<el-table-column prop="location" label="座位位置" align="center" />
					<el-table-column label="操作" align="center">
						<template v-slot="scope">
							<el-button type="primary" @click="showSeatInfo(scope.row)">预定座位</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination style="margin-top: 20px;" background layout="prev, pager, next" :total="total"
					@current-change='currentChange' :page-size="5">
				</el-pagination>
			</el-card>
			<el-card class="box-card" v-if="indexSel==3">
				<template #header>
					<div class="card-header">
						<el-input v-model="keyWord" placeholder="请输入书籍名称" style="width: 200px;margin-right: 20px;" />
						<el-button type="primary"
							@click="currentPage=1,tableData.length=0,getBorrowList()">搜索</el-button>
            <span style="font-size: 16px; color: #336699;margin-left: 20px;margin-top: 5px">归还提醒：请注意借阅时长，在规定时间内归还</span>
					</div>
				</template>
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="bookNo" label="编号" align="center" />
					<el-table-column prop="bookName" label="名称" align="center" />
					<el-table-column label="开始时间" align="center">
						<template v-slot="scope">
							{{scope.row.beginDate.join('-')}}
						</template>
					</el-table-column>
					<el-table-column label="结束时间" align="center">
						<template v-slot="scope">
							{{scope.row.endDate.join('-')}}
						</template>
					</el-table-column>

					<el-table-column prop="borrowDay" label="时长(天)" align="center" />
					<el-table-column label="状态" align="center">
						<template v-slot="scope">
							<div v-if="scope.row.status==1">已归还</div>
							<div v-if="scope.row.status==0" style="color: red;">未归还</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template v-slot="scope">
							<el-button v-if="scope.row.status==0" type="primary"
								@click="backJyClick(scope.row)">归还</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination style="margin-top: 20px;" background layout="prev, pager, next" :total="total"
					@current-change='currentChange' :page-size="5">
				</el-pagination>
			</el-card>
			<el-card class="box-card" v-if="indexSel==4">
				<template #header>
					<div class="card-header">
						<el-input v-model="keyWord" placeholder="请输入座位编号" style="width: 200px;margin-right: 20px;" />
						<el-button type="primary"
							@click="currentPage=1,tableData.length=0,getSeatReserveList()">搜索</el-button>
            <span style="font-size: 16px; color: #336699;margin-left: 20px;margin-top: 5px">超时提醒：请注意预定时间，不要超时</span>
					</div>
				</template>
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="seatNo" label="座位编号" align="center" />
					<el-table-column label="开始时间" align="center">
						<template v-slot="scope">
							{{scope.row.beginTime.slice(0,3).join('-')}}&nbsp;&nbsp;
							{{scope.row.beginTime.slice(3,5).join(':')}}0
						</template>
					</el-table-column>
					<el-table-column label="结束时间" align="center">
						<template v-slot="scope">
							{{scope.row.endTime.slice(0,3).join('-')}}&nbsp;&nbsp;
							{{scope.row.endTime.slice(3,5).join(':')}}0
						</template>
					</el-table-column>
					<el-table-column prop="reserveMinutes" label="预定时长(分钟)" align="center" />
					<el-table-column prop="caozuo" label="操作" align="center">
						<template v-slot="scope">
							<el-button type="danger" @click="delReserve(scope.row.id)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-card>

		</el-main>
	</div>
</template>


<script setup lang="ts">
	import { ElMessage, ElMessageBox } from "element-plus";
  import IatRecorder  from '@/utils/IatRecorder.js'
  const iatRecorder = new IatRecorder('en_us','mandarin','9abbbfb0')//小语种-中文方言-appId
	import {

		getBookList, addBookBorrow, borrowList,
		returnBook, getSeatList,
		getSeatReserve, delSeatReserve, listReserveBySeat,
		addSeatReserve
	} from '@/api/Forth/index.js'
	import {
		onMounted,
		reactive,
		Ref,
		ref
	} from "vue";
	const logoTextShow : Ref<boolean> = ref(true);
	const indexSel : Ref<number> = ref(1);
	const tableData = reactive([
		{}
	])
	onMounted(() => {
		getFunByIndexSel()
	})
	const total : Ref<number> = ref(0);
	const currentPage : Ref<number> = ref(1);
	const keyWord : Ref<string> = ref('');

  function translationStart(){
    iatRecorder.start()
  }
  function translationStop(){
    iatRecorder.onTextChange = function(text){
      let inputText = text
      keyWord.value = inputText.substring(0, inputText.length - 1);//文字处理，因为不知道为什么识别输出的后面都带‘。’，这个方法是去除字符串最后一位
    }
    iatRecorder.stop()
  }

	// 左侧不同菜单请求
	function selectINdex(e : any) {
		currentPage.value = 1
		indexSel.value = e
		tableData.length = 0
		keyWord.value = ''
		getFunByIndexSel()
	}
	function getFunByIndexSel() {
		if (indexSel.value == 1) {
			getBooks()
		} else if (indexSel.value == 2) {
			console.log(123);
			seatList()
		} else if (indexSel.value == 3) {
			getBorrowList()
		} else if (indexSel.value == 4) {
			getSeatReserveList()
		}
	}
	// 分页
	function currentChange(e : number | string) {
		currentPage.value = e
		getFunByIndexSel()
	}
	//获取书籍列表
	function getBooks() {
		let query : any = {
			pageNum: currentPage.value,
			pageSize: 5,
		}
		if (keyWord.value) {
			query.word = keyWord.value
		}
		getBookList(query).then((res : any) => {
			total.value = res.data.data.total
			tableData.length = 0
			tableData.push(...res.data.data.records)
		})
	}
	// 借阅
	const selBookObj = reactive({});
	const timePick : Ref<boolean> = ref(false);
	const timeData : Ref<string> = ref("");
	function showJyPick(e : any) {
		timePick.value = true
		Object.assign(selBookObj, e)
	}
	function confirmJyTime() {//选择完时间确认借阅
		console.log(timeData.value[0]);
		let query = {
			bookNo: selBookObj.bookNo,
			beginDate: dateFormat(timeData.value[0], 'yyyy-MM-dd'),
			endDate: dateFormat(timeData.value[1], 'yyyy-MM-dd'),
			userId: 1
		}
		addBookBorrow(query).then((res : any) => {
			ElMessage({ message: res.data.message+`,您的归还时间为：${dateFormat(timeData.value[1], 'yyyy-MM-dd')}`, type: 'success', showClose: true })
			timePick.value = false
			timeData.value = ''
			getBooks()
		})
	}
	// 归还
	function backJyClick(e : any) {
		returnBook({ borrowId: e.id }).then((res : any) => {
			ElMessage({ message: res.data.message, type: 'success', showClose: true })
			getBorrowList()
		})
	}
	// 借阅记录列表
	function getBorrowList() {
		let query : any = {
			pageNum: currentPage.value,
			pageSize: 5,
			userId: 1,
			word: keyWord.value
		}
		borrowList(query).then((res : any) => {
			total.value = res.data.data.total
			tableData.length = 0
			tableData.push(...res.data.data.records)
		})
	}
	//获取座位列表
	function seatList() {
		let query : any = {
			pageNum: currentPage.value,
			pageSize: 5,
		}
		getSeatList(query).then((res : any) => {
			total.value = res.data.data.total
			tableData.length = 0
			tableData.push(...res.data.data.records)
		})
	}
	//获取座位预订信息
	const selSeatObj:any = reactive({});
	const seatPick : Ref<boolean> = ref(false);
	const seatData:Ref<string>  =  ref('');
	function showSeatInfo(row : any) {
		Object.assign(selSeatObj, row)
		seatData.value = ''
		isContinuityArr.value=true
		listReserveBySeat({ seatId: row.id }).then((res : any) => {
			let data = res.data.data;
			for (let i = 0; i < data.length; i++) {
				if(data[i].status==1){
					seatTimeList.splice(i,1)
				}
			}
			seatPick.value = true
		})
	}
	//判断一串数字是否是连续的
	const isContinuityNum = (num: number[] | number) => {
	  let array = [];
	  if (num instanceof Array) {
	    array = [...num];
	  } else {
	    array = Array.from(num.toString()); //转换为数组
	  }
	
	  let i = array[0];
	  let isContinuation = true;
	  for (let e in array) {
	    if (array[e] != i) {
	      isContinuation = false;
	      break;
	    }
	    i++;
	  }
	  return isContinuation;
	};
	const isContinuityArr:Ref<boolean> = ref(true)
	function changeSeatTime(e:any){
		isContinuityArr.value = isContinuityNum(e.sort((a,b) => a-b))
		if(!isContinuityNum(e.sort((a,b) => a-b))){
			ElMessage({ message:'请选择连续的时间段', type: 'error', showClose: true })
		}
	}
	//确认座位预定
	const seatTimeList = reactive([
		{ label: '8:00-9:00', value: 8,disabled: false },
		{ label: '9:00-10:00', value: 9, disabled: false },
		{ label: '10:00-11:00', value: 10, disabled: false },
		{ label: '11:00-12:00', value: 11, disabled: false },
		{ label: '12:00-13:00', value: 12, disabled: false },
		{ label: '13:00-14:00', value: 13, disabled: false },
		{ label: '14:00-15:00', value: 14, disabled: false},
		{ label: '15:00-16:00', value: 15, disabled: false},
		{ label: '16:00-17:00', value: 16, disabled: false},
		{ label: '17:00-18:00', value: 17, disabled: false},
		{ label: '18:00-19:00', value: 18, disabled: false},
		{ label: '19:00-20:00', value: 19, disabled: false},
		{ label: '20:00-21:00', value: 20, disabled: false},
		{ label: '21:00-22:00', value: 21, disabled: false}])
	function confirmSeatTime() {
		let query={
			seatId:selSeatObj.id,
			userId:1,
			timeString:seatData.value.join(',')
		}
		if(!seatData.value) {
			return ElMessage({ message:'请选择时间', type: 'error', showClose: true })
		}
		if(!isContinuityArr.value) {
			seatData.value = ''
			return ElMessage({ message:'请选择连续的时间段', type: 'error', showClose: true })
		}
		addSeatReserve(query).then((res : any) => {
			seatPick.value = false
			ElMessage({ message: res.data.message+`,您的座位预定结束时间为当天：${seatData.value[seatData.value.length-1]}点`, type: 'success', showClose: true })
			seatList()
		})
	}
	// 获取座位预订记录
	function getSeatReserveList() {
		let query : any = {
			pageNum: currentPage.value,
			pageSize: 5,
			userId: 1,
			word: keyWord.value
		}
		getSeatReserve(query).then((res : any) => {
			total.value = res.data.data.total
			tableData.length = 0
			tableData.push(...res.data.data.records)
		})
	}
	//删除预定座位
	function delReserve(id) {
		ElMessageBox.confirm(
			'此操作将删除这条记录，请确认是否删除',
			'Warning',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			delSeatReserve({ reserveId: id }).then((res : any) => {
				ElMessage({ message: res.data.message, type: 'success', showClose: true })
				getSeatReserveList()
			})
		})

	}
	// 语音识别
	// 时间格式化
	const dateFormat = (value, dateFormat) => {
		let date = new Date(Number(value));
		if (date.toString() === 'Invalid Date') {
			date = new Date(value.replace(/\-/g, "/"));
		}
		let time = {
			Year: 0,
			TYear: '0',
			Month: 0,
			TMonth: '0',
			Day: 0,
			TDay: '0',
			Hour: 0,
			THour: '0',
			hour: 0,
			Thour: '0',
			Minute: 0,
			TMinute: '0',
			Second: 0,
			TSecond: '0',
			Millisecond: 0
		};
		time.Year = date.getFullYear();
		time.TYear = String(time.Year).substr(2);
		time.Month = date.getMonth() + 1;
		time.TMonth = time.Month < 10 ? "0" + time.Month : String(time.Month);
		time.Day = date.getDate();
		time.TDay = time.Day < 10 ? "0" + time.Day : String(time.Day);
		time.Hour = date.getHours();
		time.THour = time.Hour < 10 ? "0" + time.Hour : String(time.Hour);
		time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
		time.Thour = time.hour < 10 ? "0" + time.hour : String(time.hour);
		time.Minute = date.getMinutes();
		time.TMinute = time.Minute < 10 ? "0" + time.Minute : String(time.Minute);
		time.Second = date.getSeconds();
		time.TSecond = time.Second < 10 ? "0" + time.Second : String(time.Second);
		time.Millisecond = date.getMilliseconds();

		return dateFormat.replace(/yyyy/ig, String(time.Year))
			.replace(/yyy/ig, String(time.Year))
			.replace(/yy/ig, time.TYear)
			.replace(/y/ig, time.TYear)
			.replace(/MM/g, time.TMonth)
			.replace(/M/g, String(time.Month))
			.replace(/dd/ig, time.TDay)
			.replace(/d/ig, String(time.Day))
			.replace(/HH/g, time.THour)
			.replace(/H/g, String(time.Hour))
			.replace(/hh/g, time.Thour)
			.replace(/h/g, String(time.hour))
			.replace(/mm/g, time.TMinute)
			.replace(/m/g, String(time.Minute))
			.replace(/ss/ig, time.TSecond)
			.replace(/s/ig, String(time.Second))
			.replace(/fff/ig, String(time.Millisecond))
	}
</script>

<style scoped>
	.card-header {
		display: flex;
		justify-content: flex-start;
	}
</style>